package com.huaao.micropolice.root.controllers.system;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.huaao.micropolice.common.util.JsonUtil;
import com.huaao.micropolice.core.common.gson.GsonSimpleFilter;
import com.huaao.micropolice.core.model.system.Area;
import com.huaao.micropolice.core.model.system.Dept;
import com.huaao.micropolice.core.service.system.DeptService;
import com.huaao.micropolice.root.controllers.BaseController;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("system/dept")
public class DeptController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private DeptService deptService;
	private static JsonConfig jsonConfig = new JsonConfig();
	static{
		jsonConfig.setExcludes(new String[]{"children","parent","area","handler","hibernateLazyInitializer"});
	}
	
	@RequestMapping("index.do")
	public String index() {
		return "/system/dept/index";
	}
 
	@RequestMapping("save.do")
	public ResponseEntity<String> save(Dept item) {
		if(StringUtils.isEmpty(item.getId())){
			deptService.save(item);
		}else{
			deptService.update(item);
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(successMap()));
	}
	
 
	@RequestMapping("del.do")
	public ResponseEntity<String> del(String id) {
		try {
			deptService.del(id);
			return super.ajaxModel(JSON, JsonUtil.toJson(successMap()));
		} catch (Exception e) {
			return super.ajaxModel(JSON, JsonUtil.toJson(failMap(e.getMessage())));
		}
		
	}
	
	@RequestMapping(value="findListJson.do",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String findListJson(String nodeid){
		List<Dept> list = deptService.findByDeptParentId(nodeid);
		String result = JSONArray.fromObject(list.toArray(),jsonConfig).toString();
		return result;
	}
	
	@RequestMapping(value="findAllJson.do",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String findAllJson(){
		List<Dept> list = deptService.findAll();
		String result = JSONArray.fromObject(list.toArray(),jsonConfig).toString();
		return result;
	}
}
